Introduction to Open Data Science - Course Project

1. Introduction

About the course

The course introduces some basic statistical analysis methods and open research tools to analyze data, and to document and share code and results. The course consists of seven weekly meetings with the following topics:

  • Start me up!
  • Regression and model validation
  • Logistic regression
  • Clustering and classification
  • Dimensionality reduction techniques
  • Analysis of longitudinal data
  • Kimmo’s textbook, special edition

The course is organized online and is organized by Doctoral School in Humanities and Social Sciences.

About me

I’m a PhD student in the University of Helsinki and the topic of my PhD thesis is Projections of Population Health Outcomes. I’m working at the Finnish Institute for Health and Welfare (THL) as a statistical researcher. I currently have a busy schedule but I was happy to squeeze this course into it although my supervisor told me about this course already a few years ago. I’m looking forward for participating in IODS and getting an overview about the tools used for documenting and sharing R-code.

The link to my GitHub repository.


2. Regression and model validation

Data

In this week analysis we use JYTOPKYS2 dataset which contains survey variables related to students’ learning and teaching. The analysis dataset consists of 166 students and 7 variables. There are no missing values in the dataset. The dataset includes following variables:

  • gender (binary variable)
    • either F=female or M=male
  • age (numeric variable with integer values)
    • in years, derived from the date of birth
  • attitude (global attitude towards statistics, numeric variable)
    • mean of ten items relating to attitude towards statistics. Each item has integer values 1-5
  • deep (deep learning approach, numeric variable)
    • mean of twelve items relating to deep learning. Each item has integer values 1-5
  • stra (strategic learning approach, numeric variable)
    • mean of eight items relating to strategic learning. Each item has integer values 1-5
  • surf (surface learning approach, numeric variable)
    • mean of twelve factors relating to surface learning. Each item has integer values 1-5
  • points (total exam points, numeric variable with integer values)
#reading dataset
analysis_data <- read.csv(file='/home/jkox/Git/proj/IODS-project/data/learning2014.csv')
analysis_data$gender <- factor(analysis_data$gender) #setting gender as factor

dim(analysis_data) #the dimensions of the dataset
## [1] 166   7
str(analysis_data) #the structure of the dataset
## 'data.frame':    166 obs. of  7 variables:
##  $ gender  : Factor w/ 2 levels "F","M": 1 2 1 2 2 1 2 1 2 1 ...
##  $ age     : int  53 55 49 53 49 38 50 37 37 42 ...
##  $ attitude: num  3.7 3.1 2.5 3.5 3.7 3.8 3.5 2.9 3.8 2.1 ...
##  $ deep    : num  3.58 2.92 3.5 3.5 3.67 ...
##  $ stra    : num  3.38 2.75 3.62 3.12 3.62 ...
##  $ surf    : num  2.58 3.17 2.25 2.25 2.83 ...
##  $ points  : int  25 12 24 10 22 21 21 31 24 26 ...
head(analysis_data,10) #the first 10 rows of the dataset
##    gender age attitude     deep  stra     surf points
## 1       F  53      3.7 3.583333 3.375 2.583333     25
## 2       M  55      3.1 2.916667 2.750 3.166667     12
## 3       F  49      2.5 3.500000 3.625 2.250000     24
## 4       M  53      3.5 3.500000 3.125 2.250000     10
## 5       M  49      3.7 3.666667 3.625 2.833333     22
## 6       F  38      3.8 4.750000 3.625 2.416667     21
## 7       M  50      3.5 3.833333 2.250 1.916667     21
## 8       F  37      2.9 3.250000 4.000 2.833333     31
## 9       M  37      3.8 4.333333 4.250 2.166667     24
## 10      F  42      2.1 4.000000 3.500 3.000000     26

There are 110 female and 56 male in the datasets. Theee seems to be no large differences in distributions of continuous variables by gender although the mean of attitude for male is larger than the mean for female. The distribution of age is right skewed. The distributions of other continuous variables are visually normal distributed. The largest positive correlation is between points and attitude, and largest negative correlation between surf and deep.

#graphical overview:
p <- ggpairs(analysis_data, mapping = aes(), lower = list(combo = wrap("facethist", bins = 20)))
p

summary(analysis_data) #basic summaries of the variables
##  gender       age           attitude          deep            stra            surf           points     
##  F:110   Min.   :17.00   Min.   :1.400   Min.   :1.583   Min.   :1.250   Min.   :1.583   Min.   : 7.00  
##  M: 56   1st Qu.:21.00   1st Qu.:2.600   1st Qu.:3.333   1st Qu.:2.625   1st Qu.:2.417   1st Qu.:19.00  
##          Median :22.00   Median :3.200   Median :3.667   Median :3.188   Median :2.833   Median :23.00  
##          Mean   :25.51   Mean   :3.143   Mean   :3.680   Mean   :3.121   Mean   :2.787   Mean   :22.72  
##          3rd Qu.:27.00   3rd Qu.:3.700   3rd Qu.:4.083   3rd Qu.:3.625   3rd Qu.:3.167   3rd Qu.:27.75  
##          Max.   :55.00   Max.   :5.000   Max.   :4.917   Max.   :5.000   Max.   :4.333   Max.   :33.00

Linear model

Linear regression model is used to assess the relationship between target variable points and explanatory variables attitude, age and stra. The intercept of the model is statistically significant. The beta coefficients of attitude and stra are larger than zero meaning they are positively associated with points. On the contrary, age is negatively associated with points. However, t-test results show that only the relationship between points and attitude is statistically significant. This means that with the probability of 0.00025 the beta coefficient of attitude is zero (very unlikely). The beta coefficients of age and stra have p-values larger than 0.05 and are thus non-significant.

Since age is the variable with the largest p-value, linear model is fitted without it. In this second model the relationship between points and stra remains non-significant so a third model with only attitude as an explanatory variable is fitted. The intercept of the final model is 11.64 and the beta coefficient of attitude is 3.53. The intercept can be interpreted as the expected value of points when attitude equals zero. In addition, the beta coefficient of attitude is the expected increase in points when attitude increases by one unit. The multiple R squared of the final model is 0.19. This means that 19% of the variation in the data is explained by the final model.

my_model <- lm(points ~ attitude+age+stra, data = analysis_data) #model with attitude, age and stra
summary(my_model)
## 
## Call:
## lm(formula = points ~ attitude + age + stra, data = analysis_data)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -18.1149  -3.2003   0.3303   3.4129  10.7599 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 10.89543    2.64834   4.114 6.17e-05 ***
## attitude     3.48077    0.56220   6.191 4.72e-09 ***
## age         -0.08822    0.05302  -1.664   0.0981 .  
## stra         1.00371    0.53434   1.878   0.0621 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.26 on 162 degrees of freedom
## Multiple R-squared:  0.2182, Adjusted R-squared:  0.2037 
## F-statistic: 15.07 on 3 and 162 DF,  p-value: 1.07e-08
my_model2 <- lm(points ~ attitude+stra, data = analysis_data) #model with attitude and stra
summary(my_model2)
## 
## Call:
## lm(formula = points ~ attitude + stra, data = analysis_data)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -17.6436  -3.3113   0.5575   3.7928  10.9295 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)   8.9729     2.3959   3.745  0.00025 ***
## attitude      3.4658     0.5652   6.132 6.31e-09 ***
## stra          0.9137     0.5345   1.709  0.08927 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.289 on 163 degrees of freedom
## Multiple R-squared:  0.2048, Adjusted R-squared:  0.1951 
## F-statistic: 20.99 on 2 and 163 DF,  p-value: 7.734e-09
my_model3 <- lm(points ~ attitude, data = analysis_data) #model with attitude
summary(my_model3)
## 
## Call:
## lm(formula = points ~ attitude, data = analysis_data)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -16.9763  -3.2119   0.4339   4.1534  10.6645 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  11.6372     1.8303   6.358 1.95e-09 ***
## attitude      3.5255     0.5674   6.214 4.12e-09 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.32 on 164 degrees of freedom
## Multiple R-squared:  0.1906, Adjusted R-squared:  0.1856 
## F-statistic: 38.61 on 1 and 164 DF,  p-value: 4.119e-09
p <- qplot(attitude, points, data = analysis_data) + geom_smooth(method = "lm") #plot
p
## `geom_smooth()` using formula 'y ~ x'

Model diagnostic plots

Linear model makes several assumptions. These assumptions include that:

  1. The relationship between the target variable and the explanatory variable is linear.
  2. The residual errors are normally distributed.
  3. The residuals have a constant variance (homoscedasticity).

The validity of these assumptions should be checked when using linear regression. Also, the presence of influential values in the data should be checked.

The model diagnostic plots of the final model are presented below. Residuals vs. fitted plot can be used to check the assumptions 1 and 3. Now, a horizontal line is an indication for a linear relationship. However, there seems to be heteroscedasticity present since the spread of the residuals is not approximately the same across the x-axis. Normal Q-Q plot indicates that there seems to be a violation of assumption 2, since the residuals are not following the straight line at the ends of the line.

Residuals vs Leverage plot is used to check whether there are outliers or data points with high leverage. Outliers can be identified by examining the standardized residuals of data points. Cook’s distance measures the influence of the data points as a combination of leverage and residual size. Data points with three largest Cook’s distances are labelled in Residuals vs Leverage plot. There are no points outside the red dashed line so there are no influential data points.

par(mfrow=c(2,2))
plot(my_model3,1)
plot(my_model3,2)
plot(my_model3,5)


3. Logistic regression

Data

In this week analysis we use Student performance Data Set which contains information about student performance in mathematics and Portuguese language in secondary education of two Portuguese schools. The data attributes include student grades, demographic, social and school related features, and it was collected by using school reports and questionnaires. The analysis dataset consists of 370 students and 51 variables. The full description of dataset is available in here.

#reading dataset
pormath <- read.csv(file='/home/jkox/Git/proj/IODS-project/data/pormath.csv')

#names of the variables
names(pormath)
##  [1] "school"     "sex"        "age"        "address"    "famsize"    "Pstatus"    "Medu"       "Fedu"      
##  [9] "Mjob"       "Fjob"       "reason"     "guardian"   "traveltime" "studytime"  "schoolsup"  "famsup"    
## [17] "activities" "nursery"    "higher"     "internet"   "romantic"   "famrel"     "freetime"   "goout"     
## [25] "Dalc"       "Walc"       "health"     "n"          "id.p"       "id.m"       "failures"   "paid"      
## [33] "absences"   "G1"         "G2"         "G3"         "failures.p" "paid.p"     "absences.p" "G1.p"      
## [41] "G2.p"       "G3.p"       "failures.m" "paid.m"     "absences.m" "G1.m"       "G2.m"       "G3.m"      
## [49] "alc_use"    "high_use"   "cid"
dim(pormath) #the dimensions of the dataset
## [1] 370  51
str(pormath) #the structure of the dataset
## 'data.frame':    370 obs. of  51 variables:
##  $ school    : chr  "GP" "GP" "GP" "GP" ...
##  $ sex       : chr  "F" "F" "F" "F" ...
##  $ age       : int  15 15 15 15 15 15 15 15 15 15 ...
##  $ address   : chr  "R" "R" "R" "R" ...
##  $ famsize   : chr  "GT3" "GT3" "GT3" "GT3" ...
##  $ Pstatus   : chr  "T" "T" "T" "T" ...
##  $ Medu      : int  1 1 2 2 3 3 3 2 3 3 ...
##  $ Fedu      : int  1 1 2 4 3 4 4 2 1 3 ...
##  $ Mjob      : chr  "at_home" "other" "at_home" "services" ...
##  $ Fjob      : chr  "other" "other" "other" "health" ...
##  $ reason    : chr  "home" "reputation" "reputation" "course" ...
##  $ guardian  : chr  "mother" "mother" "mother" "mother" ...
##  $ traveltime: int  2 1 1 1 2 1 2 2 2 1 ...
##  $ studytime : int  4 2 1 3 3 3 3 2 4 4 ...
##  $ schoolsup : chr  "yes" "yes" "yes" "yes" ...
##  $ famsup    : chr  "yes" "yes" "yes" "yes" ...
##  $ activities: chr  "yes" "no" "yes" "yes" ...
##  $ nursery   : chr  "yes" "no" "yes" "yes" ...
##  $ higher    : chr  "yes" "yes" "yes" "yes" ...
##  $ internet  : chr  "yes" "yes" "no" "yes" ...
##  $ romantic  : chr  "no" "yes" "no" "no" ...
##  $ famrel    : int  3 3 4 4 4 4 4 4 4 4 ...
##  $ freetime  : int  1 3 3 3 2 3 2 1 4 3 ...
##  $ goout     : int  2 4 1 2 1 2 2 3 2 3 ...
##  $ Dalc      : int  1 2 1 1 2 1 2 1 2 1 ...
##  $ Walc      : int  1 4 1 1 3 1 2 3 3 1 ...
##  $ health    : int  1 5 2 5 3 5 5 4 3 4 ...
##  $ n         : int  2 2 2 2 2 2 2 2 2 2 ...
##  $ id.p      : int  1096 1073 1040 1025 1166 1039 1131 1069 1070 1106 ...
##  $ id.m      : int  2096 2073 2040 2025 2153 2039 2131 2069 2070 2106 ...
##  $ failures  : int  0 1 0 0 1 0 1 0 0 0 ...
##  $ paid      : chr  "yes" "no" "no" "no" ...
##  $ absences  : int  3 2 8 2 5 2 0 1 9 10 ...
##  $ G1        : int  10 10 14 10 12 12 11 10 16 10 ...
##  $ G2        : int  12 8 13 10 12 12 6 10 16 10 ...
##  $ G3        : int  12 8 12 9 12 12 6 10 16 10 ...
##  $ failures.p: int  0 0 0 0 0 0 0 0 0 0 ...
##  $ paid.p    : chr  "yes" "no" "no" "no" ...
##  $ absences.p: int  4 2 8 2 2 2 0 0 6 10 ...
##  $ G1.p      : int  13 13 14 10 13 11 10 11 15 10 ...
##  $ G2.p      : int  13 11 13 11 13 12 11 10 15 10 ...
##  $ G3.p      : int  13 11 12 10 13 12 12 11 15 10 ...
##  $ failures.m: int  1 2 0 0 2 0 2 0 0 0 ...
##  $ paid.m    : chr  "yes" "no" "yes" "yes" ...
##  $ absences.m: int  2 2 8 2 8 2 0 2 12 10 ...
##  $ G1.m      : int  7 8 14 10 10 12 12 8 16 10 ...
##  $ G2.m      : int  10 6 13 9 10 12 0 9 16 11 ...
##  $ G3.m      : int  10 5 13 8 10 11 0 8 16 11 ...
##  $ alc_use   : num  1 3 1 1 2.5 1 2 2 2.5 1 ...
##  $ high_use  : logi  FALSE TRUE FALSE FALSE TRUE FALSE ...
##  $ cid       : int  3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 ...
head(pormath,10) #the first 10 rows of the dataset
##    school sex age address famsize Pstatus Medu Fedu     Mjob     Fjob     reason guardian traveltime
## 1      GP   F  15       R     GT3       T    1    1  at_home    other       home   mother          2
## 2      GP   F  15       R     GT3       T    1    1    other    other reputation   mother          1
## 3      GP   F  15       R     GT3       T    2    2  at_home    other reputation   mother          1
## 4      GP   F  15       R     GT3       T    2    4 services   health     course   mother          1
## 5      GP   F  15       R     GT3       T    3    3 services services reputation    other          2
## 6      GP   F  15       R     GT3       T    3    4 services   health     course   mother          1
## 7      GP   F  15       R     GT3       T    3    4 services  teacher     course   father          2
## 8      GP   F  15       R     LE3       T    2    2   health services reputation   mother          2
## 9      GP   F  15       R     LE3       T    3    1    other    other reputation   father          2
## 10     GP   F  15       U     GT3       A    3    3    other   health reputation   father          1
##    studytime schoolsup famsup activities nursery higher internet romantic famrel freetime goout Dalc Walc
## 1          4       yes    yes        yes     yes    yes      yes       no      3        1     2    1    1
## 2          2       yes    yes         no      no    yes      yes      yes      3        3     4    2    4
## 3          1       yes    yes        yes     yes    yes       no       no      4        3     1    1    1
## 4          3       yes    yes        yes     yes    yes      yes       no      4        3     2    1    1
## 5          3        no    yes        yes     yes    yes      yes      yes      4        2     1    2    3
## 6          3       yes    yes        yes     yes    yes      yes       no      4        3     2    1    1
## 7          3        no    yes         no     yes    yes      yes      yes      4        2     2    2    2
## 8          2       yes    yes         no     yes    yes      yes       no      4        1     3    1    3
## 9          4        no    yes         no      no    yes      yes       no      4        4     2    2    3
## 10         4       yes     no         no     yes    yes       no       no      4        3     3    1    1
##    health n id.p id.m failures paid absences G1 G2 G3 failures.p paid.p absences.p G1.p G2.p G3.p failures.m
## 1       1 2 1096 2096        0  yes        3 10 12 12          0    yes          4   13   13   13          1
## 2       5 2 1073 2073        1   no        2 10  8  8          0     no          2   13   11   11          2
## 3       2 2 1040 2040        0   no        8 14 13 12          0     no          8   14   13   12          0
## 4       5 2 1025 2025        0   no        2 10 10  9          0     no          2   10   11   10          0
## 5       3 2 1166 2153        1  yes        5 12 12 12          0    yes          2   13   13   13          2
## 6       5 2 1039 2039        0   no        2 12 12 12          0     no          2   11   12   12          0
## 7       5 2 1131 2131        1   no        0 11  6  6          0     no          0   10   11   12          2
## 8       4 2 1069 2069        0   no        1 10 10 10          0     no          0   11   10   11          0
## 9       3 2 1070 2070        0   no        9 16 16 16          0     no          6   15   15   15          0
## 10      4 2 1106 2106        0   no       10 10 10 10          0     no         10   10   10   10          0
##    paid.m absences.m G1.m G2.m G3.m alc_use high_use  cid
## 1     yes          2    7   10   10     1.0    FALSE 3001
## 2      no          2    8    6    5     3.0     TRUE 3002
## 3     yes          8   14   13   13     1.0    FALSE 3003
## 4     yes          2   10    9    8     1.0    FALSE 3004
## 5     yes          8   10   10   10     2.5     TRUE 3005
## 6     yes          2   12   12   11     1.0    FALSE 3006
## 7      no          0   12    0    0     2.0    FALSE 3007
## 8     yes          2    8    9    8     2.0    FALSE 3008
## 9      no         12   16   16   16     2.5     TRUE 3009
## 10     no         10   10   11   11     1.0    FALSE 3010

Hypothesis and data exploration

Four interesting variables are selected from the analysis dataset, and the association of those variables with high/low alcohol use (high_use) is examined. The four selected variables are :

  • absences (the mean of school absences from classes of mathematics and Portuguese language)
  • health (current health status)
  • age
  • sex

The hypothesis about the association of these variables with alcohol use is that the mean of absences is higher and health status is lower among those with high alcohol use. Furthermore, it is assumed that high alcohol use is more frequent among men than among women, and that age is positively associated with high alcohol use.

There are 111 high alcohol users and 259 low alcohol users in the data. The age range is 15 to 22 years, and there are 195 women and 175 men in the analysis dataset. The mean of absences varies from 0 to 45. When looking the graphical presentation of the pairwise associations between the variables, there seems to be more absences among the high alcohol users. Also, high alcohol users are older than low alcohol users, and the proportion of high alcohol use is higher among men than among women, However, there seems to be no association between high alcohol use and health status. Furthermore, looking the proportions of health status classes by alcohol use, there seems to be no difference.

These findings are in line with the prior hypothesis, except for health status, where a lower health was assumed to be associated with high alcohol use.

summary(subset(pormath, select=c('high_use','absences','health','sex','age')))
##   high_use          absences          health          sex                 age       
##  Mode :logical   Min.   : 0.000   Min.   :1.000   Length:370         Min.   :15.00  
##  FALSE:259       1st Qu.: 1.000   1st Qu.:3.000   Class :character   1st Qu.:16.00  
##  TRUE :111       Median : 3.000   Median :4.000   Mode  :character   Median :17.00  
##                  Mean   : 4.511   Mean   :3.562                      Mean   :16.58  
##                  3rd Qu.: 6.000   3rd Qu.:5.000                      3rd Qu.:17.00  
##                  Max.   :45.000   Max.   :5.000                      Max.   :22.00
table(pormath$sex)
## 
##   F   M 
## 195 175
p <- ggpairs(subset(pormath, select=c('high_use','absences','health','sex','age')), mapping = aes(col=high_use,alpha=0.3), lower = list(combo = wrap("facethist", bins = 20)))
p

table(pormath$high_use,pormath$health) %>% prop.table(1)
##        
##                 1         2         3         4         5
##   FALSE 0.1351351 0.1081081 0.2355212 0.1737452 0.3474903
##   TRUE  0.0990991 0.1261261 0.1711712 0.1531532 0.4504505

Logistic regression

Logistic regression model was fitted with high alcohol use as target variables and the four selected variables as explanatory variables.

The mean of absences an sex have statistically significant association with high alcohol use. The odds ratio of absences is 1.097 with the interpretation that the expected increase in the odds of being a high alcohol user in 9.7%, for a one-unit increase in absences. Likewise, the expected odds of being a high alcohol user is 2.72 higher for men than for women.

The results indicate that the prior hypothesis concerning absences and sex was correct. However, there is not enough evidence for the hypothesis that older age and lower health were positively associated wth high alcohol use.

m <- glm(high_use ~ absences + health + sex + age, data = pormath, family = "binomial")
summary(m)
## 
## Call:
## glm(formula = high_use ~ absences + health + sex + age, family = "binomial", 
##     data = pormath)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.3556  -0.8424  -0.6086   1.0700   2.1619  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept) -4.87786    1.75660  -2.777  0.00549 ** 
## absences     0.09264    0.02344   3.952 7.75e-05 ***
## health       0.09525    0.08878   1.073  0.28332    
## sexM         1.00325    0.24684   4.064 4.82e-05 ***
## age          0.16347    0.10202   1.602  0.10907    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 452.04  on 369  degrees of freedom
## Residual deviance: 412.11  on 365  degrees of freedom
## AIC: 422.11
## 
## Number of Fisher Scoring iterations: 4
Coeff <- coef(m) %>% exp
CI <- confint(m) %>% exp
## Waiting for profiling to be done...
cbind(Coeff,CI)
##                   Coeff        2.5 %    97.5 %
## (Intercept) 0.007613307 0.0002295193 0.2288702
## absences    1.097072080 1.0500011255 1.1512256
## health      1.099938481 0.9259125849 1.3125241
## sexM        2.727130101 1.6910032352 4.4591635
## age         1.177595137 0.9652572862 1.4414744

Predictions

The model with only absences and sex as explanatory variables is fitted and model performance is evaluated. 91% of the students are predicted as low alcohol users and 9% are predicted as high alcohol users. 68% of students are both low alcohol users and predicted as low alcohol users. The corresponding figure for high alcohol users is 7%. The training error is 25%. This performance is compared to simple guessing strategies: all students are predicted to be low alcohol users and high alcohol users. The performance of these strategies was worse than the training error.

m2 <- glm(high_use ~ absences + sex, data = pormath, family = "binomial")

probabilities <- predict(m2, type = "response")
pormath <- mutate(pormath, probability = probabilities)
pormath <- mutate(pormath, prediction = probability>0.5)

# tabulate the target variable versus the predictions
with(pormath,table(high_use, prediction))
##         prediction
## high_use FALSE TRUE
##    FALSE   251    8
##    TRUE     86   25
# table with proportions
table(high_use = pormath$high_use, prediction = pormath$prediction) %>% prop.table %>% addmargins()
##         prediction
## high_use      FALSE       TRUE        Sum
##    FALSE 0.67837838 0.02162162 0.70000000
##    TRUE  0.23243243 0.06756757 0.30000000
##    Sum   0.91081081 0.08918919 1.00000000
# plot
g <- ggplot(pormath, aes(x = probability, y = high_use, col=prediction)) + geom_point()
g

# define a loss function (mean prediction error)
loss_func <- function(class, prob) {
  n_wrong <- abs(class - prob) > 0.5
  mean(n_wrong)
}

#training error:
loss_func(class = pormath$high_use, prob = pormath$probability)
## [1] 0.2540541
#simple guessing strategies:
loss_func(class = pormath$high_use, prob = 0)
## [1] 0.3
loss_func(class = pormath$high_use, prob = 1)
## [1] 0.7

4. Classification and clustering

Data

In this week analysis we use data consisting of housing values in suburbs of Boston from R package MASS. The data has information about socio-economic, business, geographical, and environmental characteristics of towns in Boston. The data has 506 rows and 14 columns with all the variables numeric, with the exception of dummy variable chas . The description of the data is here.

The distributions of crim, zn, dis, and black are very skewed, while the distributions of indus, rad and tax are bimodal. The largest correlations are between indus and nox (positive), indus and dis (negative), indus and tax (positive), nox and age (positive), nox and dis (negative), age and dis (negative), rad and tax (positive), and lstat and medv (negative).

data("Boston") #loading data

str(Boston) #structure
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
dim(Boston) #dimensions
## [1] 506  14
summary(Boston)
##       crim                zn             indus            chas              nox               rm       
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000   Min.   :0.3850   Min.   :3.561  
##  1st Qu.: 0.08205   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000   1st Qu.:0.4490   1st Qu.:5.886  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000   Median :0.5380   Median :6.208  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917   Mean   :0.5547   Mean   :6.285  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000   3rd Qu.:0.6240   3rd Qu.:6.623  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000   Max.   :0.8710   Max.   :8.780  
##       age              dis              rad              tax           ptratio          black       
##  Min.   :  2.90   Min.   : 1.130   Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 45.02   1st Qu.: 2.100   1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 77.50   Median : 3.207   Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 68.57   Mean   : 3.795   Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.: 94.08   3rd Qu.: 5.188   3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :100.00   Max.   :12.127   Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00
p <- ggpairs(Boston, mapping = aes(), lower = list(combo = wrap("facethist", bins = 20)))
p

The standardized data is summarized below. All the standardized variables have a mean equal to 0 and a standard deviation equal to 1. A new categorical variable crime is derived and data is divided into train and test sets.

boston_scaled <- data.frame(scale(Boston))

summary(boston_scaled)
##       crim                 zn               indus              chas              nox         
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563   Min.   :-0.2723   Min.   :-1.4644  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668   1st Qu.:-0.2723   1st Qu.:-0.9121  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109   Median :-0.2723   Median :-0.1441  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150   3rd Qu.:-0.2723   3rd Qu.: 0.5981  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202   Max.   : 3.6648   Max.   : 2.7296  
##        rm               age               dis               rad               tax             ptratio       
##  Min.   :-3.8764   Min.   :-2.3331   Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.5681   1st Qu.:-0.8366   1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.1084   Median : 0.3171   Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4823   3rd Qu.: 0.9059   3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.5515   Max.   : 1.1164   Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865
#New variable `crime` is derived:
bins <- quantile(boston_scaled$crim)
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, label = c("low","med_low","med_high","high"))
boston_scaled$crim <- NULL
boston_scaled$crime <- crime

#Dividing the data to train and test datasets:
ind <- sample(nrow(boston_scaled),  size = nrow(boston_scaled) * 0.8)
train <- boston_scaled[ind,] #training set
test <- boston_scaled[-ind,] #test set

Linear discriminant analysis (LDA)

Linear discriminant analysis is fitted on the training set with the variable crime as target variable. Then, biplot is drawn.

lda.fit <- lda(crime~., data = train)

# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

# target classes as numeric
classes <- as.numeric(train$crime)

# plot the lda results
plot(lda.fit, dimen = 2, col=classes,pch=classes)
lda.arrows(lda.fit, myscale = 2)

Predictions

The crime classes of the test set are predicted using the fitted LDA model. When tabulating the correct and the predicted values, there are nine observations with correct value “low” and predicted value “med_low”, and nine observations with correct value “med_low” and predicted value “med_high”. Otherwise the predicted values seem to correspond the correct values well.

correct_classes <- test$crime #saving crime categories
test$crime <- NULL #removing crime from test set

lda.pred <- predict(lda.fit, newdata = test)

table(correct = correct_classes, predicted = lda.pred$class)
##           predicted
## correct    low med_low med_high high
##   low       15      13        1    0
##   med_low    9      14        3    0
##   med_high   0       7       20    1
##   high       0       0        0   19

Distances

The distances between the observations in the scaled Boston data are calculated. K-means algorithm is run with number of clusters from 1 to 10 to find the optimal number of clusters. The resulting plot shows that the total of within cluster sum of squares drops most radically when the number of clusters is two. When looking at the visualization of the two clusters in relation of the variables in Boston data, we see that the distributions of indus, nox, dis, and tax by cluster separates the clusters quite well. The distribution of rm by cluster are almost identical.

data(Boston)

boston_scaled <- scale(Boston)

dist_eu <- dist(boston_scaled) #distances

set.seed(544356)

twcss <- sapply(1:10, function(k){kmeans(boston_scaled, k)$tot.withinss}) #total within cluster sum of squares

# visualize the results
qplot(x = 1:10, y = twcss, geom = 'line') + scale_x_continuous(breaks=seq(1,10,by=1)) + xlab('number of clusters') 

km <-kmeans(boston_scaled, centers = 2) #km-algorithm with the number of clusters = 2

p <- ggpairs(data.frame(boston_scaled), mapping = aes(col = factor(km$cluster), alpha=0.3), lower = list(combo = wrap("facethist", bins = 20)))
p


(more chapters to be added similarly as we proceed with the course!)